package biz.alla.market.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import biz.alla.market.web.WebConstants;
import biz.alla.market.web.controller.UserController;

public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
	HttpServletRequest httpRequest = (HttpServletRequest) request;
	HttpServletResponse httpResponse = (HttpServletResponse) response;

	HttpSession session = httpRequest.getSession(false);

	if (!isLoginRequest(httpRequest) && (session == null || session.getAttribute(WebConstants.SESSION_ATTR_USER) == null)) {
	    httpResponse.sendRedirect(UserController.VIEW_LOGIN);
	} else {
	    filterChain.doFilter(request, response);
	}
    }

    private boolean isLoginRequest(HttpServletRequest httpRequest) {
	return httpRequest.getRequestURL().toString().contains(UserController.VIEW_LOGIN);
    }

    @Override
    public void destroy() {
    }

}
